package com.mynews.activities.main.ui.recommend;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.util.Log;

import androidx.databinding.BindingAdapter;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModel;

import com.mynews.activities.App;
import com.mynews.activities.detail.DetailActivity;
import com.mynews.activities.view.PullingLayout;
import com.mynews.adapter.NewsAdapter;
import com.mynews.bean.NewsBean;
import com.mynews.databinding.FragmentRecommendBinding;
import com.mynews.utils.BmobApi;
import com.mynews.utils.Utils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class RecommendVM extends ViewModel {
    private final static List<NewsBean> data=new ArrayList<>();
    @SuppressLint("StaticFieldLeak")
    private static FragmentActivity fragmentActivity;
    @SuppressLint("StaticFieldLeak")
    private static FragmentRecommendBinding binding;
    public RecommendVM(){}
    public void setBinding(FragmentRecommendBinding binding, FragmentActivity fragmentActivity) {
        RecommendVM.binding =binding;
        RecommendVM.fragmentActivity =fragmentActivity;
        binding.setAdp(new NewsAdapter(fragmentActivity,data));
        binding.recommendList.setOnItemClickListener((parent, view, position, id) -> {
            App.newsBean=data.get(position);
            fragmentActivity.runOnUiThread(() ->fragmentActivity.startActivity(new Intent(fragmentActivity, DetailActivity.class)));
        });
        refresh(null);
    }
    public static void refresh(PullingLayout pullingLayout) {
        data.clear();
        BmobApi.get("https://api2.bmob.cn/1/classes/factor?order=-createdAt&where=" + URLEncoder.encode("{\"userId\":\"" + App.user.objectId + "\"}"), new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {}
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                try {
                    assert response.body() != null;
                    JSONObject jo = new JSONObject(response.body().string()).getJSONArray("results").getJSONObject(0);
                    double type1 = jo.getDouble("type1");
                    double type2 = jo.getDouble("type2");
                    double type3 = jo.getDouble("type3");
                    double type4 = jo.getDouble("type4");
                    double type5 = jo.getDouble("type5");
                    double type6 = jo.getDouble("type6");
                    double type7 = jo.getDouble("type7");
                    double type8 = jo.getDouble("type8");
                    double all=type1+type2+type3+type4+type5+type6+type7+type8;
                    int[] arr=new int[]{(int)(type1*10/all),(int)(type2*10/all),(int)(type3*10/all),(int)(type4*10/all),(int)(type5*10/all),(int)(type6*10/all),(int)(type7*10/all),(int)(type8*10/all)};
                    for (int i = 0; i < arr.length; i++) {
                        if (arr[i]!=0){
                            BmobApi.get("https://api2.bmob.cn/1/classes/news?order=-createdAt&count="+arr[i]+"&where="+ URLEncoder.encode("{\"type\":\""+ App.getNameByType(i+1)+"\"}"), new Callback() {
                                @Override
                                public void onFailure(@NotNull Call call, @NotNull IOException e){e.printStackTrace();}
                                @Override
                                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                    try {
                                        assert response.body() != null;
                                        JSONArray ja = new JSONObject(response.body().string()).getJSONArray("results");
                                        int i=Integer.parseInt(Objects.requireNonNull(response.request().url().queryParameter("count")));
                                        if (i>ja.length()){
                                            for (int i1 = 0; i1 < ja.length(); i1++) {
                                                JSONObject jo = ja.getJSONObject(i1);
                                                data.add(new NewsBean(jo.getString("objectId"),jo.getString("title"),jo.getString("content"),jo.getString("ownerId"),jo.getString("updatedAt"),jo.getString("type"),null));
                                            }
                                        }else{
                                            List<Integer> list = Utils.getRandomNumList(i, 0, ja.length());
                                            for (int inte :list) {
                                                JSONObject jo = ja.getJSONObject(inte);
                                                data.add(new NewsBean(jo.getString("objectId"),jo.getString("title"),jo.getString("content"),jo.getString("ownerId"),jo.getString("updatedAt"),jo.getString("type"),null));
                                            }
                                        }
                                        fragmentActivity.runOnUiThread(() -> {
                                            binding.getAdp().notifyDataSetChanged();
                                            if (pullingLayout!=null) pullingLayout.refreshFinish(0);
                                        });
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    @BindingAdapter("bindPull")
    public static void bindPull(PullingLayout pullingLayout,RecommendVM recommendVM){
        pullingLayout.setPullDownEnabled(true);
        pullingLayout.setOnRefreshListener(RecommendVM::refresh);
    }
}